using System;
using Framework;
using Framework.Network;


namespace Game
{
    public static class LoginUtility
    {
        public static string s_LoginAddress = "127.0.0.1:10002";

        public static async FVoid LoginAsync(string account, string password)
        {
            try
            {
                Session realmSession = GameEntry.Network.Create(s_LoginAddress);
                R2C_Login r2cLogin = (R2C_Login)await realmSession.Call(new C2R_Login() {Account = account, Password = password });
                realmSession.Dispose();

                Log.Info($"获取Gate Key:{r2cLogin.Key} Address:{r2cLogin.Address}");

                Session gateSession = GameEntry.Network.Create(r2cLogin.Address);
                GameEntry.Network.Session = gateSession;
                G2C_LoginGate g2cLoginGate = (G2C_LoginGate)await gateSession.Call(new C2G_LoginGate() {Key = r2cLogin.Key });

                Log.Info($"玩家 id: {g2cLoginGate.PlayerId} account: {account} 登录成功!");

                GameEntry.Player.PlayerId = g2cLoginGate.PlayerId;
                
                G2C_GetPlayerInfo g2cGetPlayerInfo = (G2C_GetPlayerInfo)await gateSession.Call(new C2G_GetPlayerInfo());
                
                Log.Info($"获取玩家信息, id:{GameEntry.Player.PlayerId}, 名字:{g2cGetPlayerInfo.PlayerInfo.Name}");

                GameEntry.Player.InitMainPlayer(g2cGetPlayerInfo.PlayerInfo);

                GameEntry.Network.AddComponent<HeartBeatComponent>();

                GameEntry.Event.BroadCast(GlobalEventType.LoginFinish);

            }
            catch (Exception e)
            {
                Log.Error(e);
            }
        }
    }
}